package middleware

import (
	"log"
	"runtime"
	"time"

	"github.com/gin-gonic/gin"
)

// MemoryStats 记录内存统计信息
type MemoryStats struct {
	Alloc      uint64
	TotalAlloc uint64
	NumGC      uint32
}

// MemoryMonitor 返回一个内存监控中间件
func MemoryMonitor() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		var m runtime.MemStats
		runtime.ReadMemStats(&m)
		startStats := MemoryStats{
			Alloc:      m.Alloc,
			TotalAlloc: m.TotalAlloc,
			NumGC:      m.NumGC,
		}

		// 处理请求
		c.Next()

		// 请求结束后再次读取内存统计
		runtime.ReadMemStats(&m)
		endStats := MemoryStats{
			Alloc:      m.Alloc,
			TotalAlloc: m.TotalAlloc,
			NumGC:      m.NumGC,
		}

		// 计算内存使用变化
		allocDiff := endStats.Alloc - startStats.Alloc
		totalAllocDiff := endStats.TotalAlloc - startStats.TotalAlloc
		gcDiff := endStats.NumGC - startStats.NumGC

		// 记录内存使用情况
		log.Printf("[Memory] Request: %s %s, Duration: %v, Alloc: %d, TotalAlloc: %d, GC: %d",
			c.Request.Method,
			c.Request.URL.Path,
			time.Since(start),
			allocDiff,
			totalAllocDiff,
			gcDiff,
		)

		// 如果内存使用增长过大，记录警告
		if allocDiff > 1024*1024 { // 1MB
			log.Printf("[Memory Warning] Large memory allocation detected: %d bytes", allocDiff)
		}
	}
}
